package com.rhb.ca.uzer.web.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.*;


import com.rhb.ca.exception.DuplicateException;
import com.rhb.ca.exception.RequiredException;
import com.rhb.ca.role.bean.Role;
import com.rhb.ca.uzer.web.struts.form.*;
import com.rhb.ca.web.struts.action.BaseDispatchAction;

public class UzerSaveAction extends BaseDispatchAction {
	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		//System.out.println("unspecified for defalut parameter!");
		return mapping.findForward("fail");
	}
	public ActionForward del(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		UzerForm oform = (UzerForm)form;
		this.getUzerBusiness().delete(oform.getUzer());
		return mapping.findForward("success");
	}
	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		UzerForm oform = (UzerForm)form;
		ActionMessages messages = new ActionMessages();
		
		oform.getUzer().getRoles().clear();
		String[] rolePks = oform.getRolePksSelected();
		if(rolePks!=null && rolePks.length>0){			
			for(int i=0; i<rolePks.length; i++){
				oform.getUzer().getRoles().add(this.getRoleBusiness().findByPk(rolePks[i]));
			}
		}
		try {
			this.getUzerBusiness().update(oform.getUzer());
		} catch (DuplicateException e) {
			messages.add("errors.duplicate", new ActionMessage("errors.duplicate",e.toString()));
			saveErrors(request, messages);
			return new ActionForward(mapping.getInput());
		} catch(RequiredException re){
			messages.add("errors.required", new ActionMessage("errors.required",re.toString()));
			saveErrors(request, messages);
		}
		return mapping.findForward("success");
	}
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		UzerForm oform = (UzerForm)form;
		ActionMessages messages = new ActionMessages();
		
		String[] rolePks = oform.getRolePksSelected();
		oform.getUzer().getRoles().clear();
		if(rolePks!=null && rolePks.length>0){			
			for(int i=0; i<rolePks.length; i++){		
				oform.getUzer().getRoles().add(this.getRoleBusiness().findByPk(rolePks[i]));
			}
		}

		try {
			this.getUzerBusiness().create(oform.getUzer());
		} catch (DuplicateException e) {
			messages.add("errors.duplicate", new ActionMessage("errors.duplicate",e.toString()));
			saveErrors(request, messages);
			return new ActionForward(mapping.getInput());
		}catch(RequiredException re){
			messages.add("errors.required", new ActionMessage("errors.required",re.toString()));
			saveErrors(request, messages);
		}
		return mapping.findForward("success");
	}	 
}
